package org.wwb.antbox.center.web.config;

import org.ant.boot.starter.dubbo.base.properties.DubboApplicationProperties;
import org.ant.boot.starter.dubbo.consumer.config.AntDubboConsumerAutoConfiguration;
import org.ant.boot.starter.dubbo.consumer.properties.DubboConsumerProperties;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.wwb.antbox.user.iservice.ServiceUserTool;

/**
 * @Author Bond
 * @Date: 2020/3/3 16:31
 * @Description: Center Dubbo 服务消费者配置
 */
@Configuration
@EnableConfigurationProperties({
        DubboConsumerProperties.class,
        DubboApplicationProperties.class})
@AutoConfigureAfter({AntDubboConsumerAutoConfiguration.class})
public class CenterDubboConsumerAutoConfiguration {

    @Autowired
    private ConsumerConfig consumerConfig;

    /**
     * Dubbo 注册中心配置
     * @return RegistryConfig
     */
    @Bean(name = "registryConfigCenter")
    @ConditionalOnMissingBean(name = "registryConfigCenter")
    @ConfigurationProperties(prefix = "org.ant.boot.dubbo.registry-center")
    public RegistryConfig registryConfig(){
        RegistryConfig registryConfig = new RegistryConfig();
        return registryConfig;
    }

    /**
     * Dubbo 元数据中心配置
     * @return
     */
    @Bean(name = "metadataReportConfig")
    @ConditionalOnMissingBean(name = "metadataReportConfig")
    public MetadataReportConfig metadataReportConfig() {
        MetadataReportConfig metadataReportConfig = new MetadataReportConfig();
        metadataReportConfig.setAddress(registryConfig().getAddress());
        return metadataReportConfig;
    }

    /**
     * 每个业务必须定义这个
     * @return
     */
    @Bean("consoleServiceTool")
    @ConditionalOnMissingBean(name = "consoleServiceTool")
    @DependsOn("registryConfigCenter")
    public ServiceUserTool serviceUserTool(){
        ServiceUserTool serviceUserTool= new ServiceUserTool();
        serviceUserTool.setRegistryConfig(registryConfig());
        serviceUserTool.setConsumerConfig(consumerConfig);
        serviceUserTool.setMetadataReportConfig(metadataReportConfig());
        return serviceUserTool;
    }
}
